package com.chat.netty.udpserver;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Data
public class UdpNettyServer implements Runnable{

    private final Logger logger = LoggerFactory.getLogger(UdpNettyServer.class);

    private int port;
    private String host;
    private ChannelHandler childChannelHandler;
    private ChannelFuture serverChannelFuture;
    private EventLoopGroup group;

    private final int timeout = 5;

    public UdpNettyServer() {

    }

    @Override
    public void run() {
        build();
    }

    /**
     * 描述：启动Netty Websocket服务器
     */
    public void build() {
        EventLoopGroup bossLoopGroup = new NioEventLoopGroup();
        try {
            long begin = System.currentTimeMillis();
            //1、创建netty bootstrap 启动类
            Bootstrap serverBootstrap = new Bootstrap();
            //2、设置boostrap 的eventLoopGroup线程组
            serverBootstrap = serverBootstrap.group(bossLoopGroup);
            //3、设置NIO UDP连接通道
            serverBootstrap = serverBootstrap.channel(NioDatagramChannel.class);
            //4、设置通道参数 SO_BROADCAST广播形式
            serverBootstrap = serverBootstrap.option(ChannelOption.SO_BROADCAST, true);
            //5、设置处理类 装配流水线
            serverBootstrap = serverBootstrap.handler(childChannelHandler);
            //6、绑定server，通过调用sync（）方法异步阻塞，直到绑定成功
            serverChannelFuture = serverBootstrap.bind(port).sync();

            long end = System.currentTimeMillis();
            logger.info("Netty Udp服务器启动完成，耗时 " + (end - begin) +" ms，已绑定端口 " + port+"监听" + serverChannelFuture.channel().localAddress());
            //7、监听通道关闭事件，应用程序会一直等待，直到channel关闭
            serverChannelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
        } finally {
            logger.info("netty udpServer close!");
            //8 关闭EventLoopGroup，
            bossLoopGroup.shutdownGracefully();
        }

    }

}
